package com.lots.service.impl;

import com.lots.context.BaseContext;
import com.lots.domain.entity.User;
import com.lots.domain.entity.UserFavorite;
import com.lots.mapper.DishDetailMapper;
import com.lots.domain.entity.DishDetail;
import com.lots.mapper.UserFavoriteMapper;
import com.lots.mapper.UserMapper;
import com.lots.service.DishDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;

@Service
public class DishDetailServiceImpl implements DishDetailService {
    @Autowired
    private DishDetailMapper dishDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserFavoriteMapper userFavoriteMapper;

    /**
     * 根基id查询菜品详情
     *
     * @param id
     * @return
     */
    @Override
    public DishDetail getDishById(Long id) {
        // 查询菜品详情
        DishDetail dishDetail = dishDetailMapper.getById(id);
        if (dishDetail == null) {
            return null; // 或抛异常：throw new RuntimeException("菜品不存在");
        }

        // 查询创建者信息
        User user = userMapper.getUserById(dishDetail.getUserId());
        if (user != null) {
            dishDetail.setName(user.getName());
            dishDetail.setAvatar(user.getAvatar());
        }
        return dishDetail;
    }

    @Override
    public Boolean getIsLiked(Long dishId) {
        //从线程中获取用户id，判断用户是否收藏了该菜
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return false;
        }
        int userFavorite = userFavoriteMapper.queryFavorite(currentUserId, dishId);
        return userFavorite > 0;
    }

}
